// 数据库准备
const mongoose = require('mongoose')
const CONNECTION_URL = `mongodb://127.0.0.1:27017/wechat`

mongoose.connect(CONNECTION_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})

mongoose.connection.on('connected', () => {
  console.log('Mongo has connected succesfully')
})

// api 服务
const cors = require('cors')
const express = require('express')
const morgan = require('morgan')
const handleError = require('./middleware/handleError')
const app = express()
app.use(morgan('dev'))
app.use(cors())
app.use(express.json())

const router = require('./router')
app.use(router)
// 统一错误处理
app.use(handleError())

const httpServer = require('http').createServer(app)

// Websocket链接
const io = require('socket.io')(httpServer, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST'],
  },
})
global.io = io
const ws = require('./utils/WebSocket')
io.on('connection', ws.connection)

httpServer.listen(3001)
